﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Web;
using System.Xml;
using System.Reflection;
using System.Net;
using He.Common;

namespace He.API.WeiXin
{
    public class MsgHandle
    {
        xml requestXml;
        xml responseXml;
        public MsgHandle()
        {
            //构造函数
            requestXml = GetRequestXml();//通过反序列化xml给属性赋值
            ResponseMsgInit();
        }

        /// <summary>
        /// 接收微信服务器发送的XML，并反序列化为xml
        /// </summary>
        /// <returns></returns>
        public xml GetRequestXml()
        {
            Stream InputStream = HttpContext.Current.Request.InputStream;
            return (xml)SerializationHelper.Load(typeof(xml), InputStream);
        }

        /// <summary>
        /// 初始化给响应的各节点赋值
        /// </summary>
        public void ResponseMsgInit()
        {
            responseXml = new xml
            {
                ToUserName = requestXml.FromUserName,
                FromUserName = requestXml.ToUserName,
                CreateTime = ObjectConvert.DateTimeToInt(DateTime.Now).ToString()
            };
        }

        /// <summary>
        /// 封装需要响应的模型
        /// </summary>
        /// <returns></returns>
        public xml ResponseNodes()
        {
            //接收文本消息
            if (requestXml.MsgType == Enums.MsgType.text.ToString())
            {
                AppendResponseByKeyword(requestXml.Content);
            }
            //接收事件推送
            else if (requestXml.MsgType == Enums.MsgType.Event.ToString().ToLower())
            {
                //关注
                if (requestXml.Event == Enums.Event.subscribe.ToString())
                {
                    //记录用户OpenId,自动创建会员
                    AddMemberInfo(requestXml.FromUserName);
                    if (Config.wx_config.follow_is_keyword == 1)
                    {
                        AppendResponseByKeyword(Config.wx_config.follow_keyword);
                    }
                    else
                    {
                        AppendResponseText(Config.wx_config.follow_msg);
                    }
                }
                //点击菜单
                else if (requestXml.Event == Enums.Event.CLICK.ToString())
                {
                    AppendResponseByKeyword(requestXml.EventKey);
                }
            }
            return responseXml;

            #region ---
            //else if (requestXML.MsgType == "location")
            //{
            //    string mapInfo = GetMapInfo(requestXML.Location_X, requestXML.Location_Y);
            //    if (mapInfo == "0")
            //    {
            //        str = string.Concat(new object[] { "<xml><ToUserName><![CDATA[", requestXML.FromUserName, "]]></ToUserName><FromUserName><![CDATA[", requestXML.ToUserName, "]]></FromUserName><CreateTime>", ConvertDateTimeInt(DateTime.Now), "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[Sorry，没有找到", mapInfo, " 的相关产品信息]]></Content><FuncFlag>0</FuncFlag></xml>" });
            //    }
            //    else
            //    {
            //        str = string.Concat(new object[] { "<xml><ToUserName><![CDATA[", requestXML.FromUserName, "]]></ToUserName><FromUserName><![CDATA[", requestXML.ToUserName, "]]></FromUserName><CreateTime>", ConvertDateTimeInt(DateTime.Now), "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[Sorry，这是 ", mapInfo, " 的产品信息：圈圈叉叉]]></Content><FuncFlag>0</FuncFlag></xml>" });
            //    }
            //}
            //else if (requestXML.MsgType == "image")
            //{
            //    int num2;
            //    int num = 10;
            //    str = string.Concat(new object[] { "<xml><ToUserName><![CDATA[", requestXML.FromUserName, "]]></ToUserName><FromUserName><![CDATA[", requestXML.ToUserName, "]]></FromUserName><CreateTime>", ConvertDateTimeInt(DateTime.Now), "</CreateTime><MsgType><![CDATA[news]]></MsgType><Content><![CDATA[]]></Content><ArticleCount>", num, "</ArticleCount><Articles>" });
            //    List<string> list = new List<string>();
            //    for (num2 = 0; num2 < 20; num2++)
            //    {
            //        list.Add("1");
            //    }
            //    string[] strArray = new string[] { "/Abstract_Pencil_Scribble_Background_Vector_main.jpg", "/balloon_tree.jpg", "/bloom.jpg", "/colorful_flowers.jpg", "/colorful_summer_flower.jpg", "/fall.jpg", "/fall_tree.jpg", "/growing_flowers.jpg", "/shoes_illustration.jpg", "/splashed_tree.jpg" };
            //    for (num2 = 0; (num2 < num) && (num2 < list.Count); num2++)
            //    {
            //        str = str + "<item><Title><![CDATA[沈阳-黑龙江]]></Title><Description><![CDATA[元旦特价：￥300 市场价：￥400]]></Description><PicUrl><![CDATA[http://www.hougelou.com" + strArray[num2] + "]]></PicUrl><Url><![CDATA[http://www.hougelou.com]]></Url></item>";
            //    }
            //    str = str + "</Articles><FuncFlag>1</FuncFlag></xml>";
            //}
            #endregion
        }

        /// <summary>
        /// 封装关键词回复
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="responseXml"></param>
        /// <returns></returns>
        public void AppendResponseByKeyword(string keyword)
        {
            BLL.wx_keyword wbll = new BLL.wx_keyword();
            Model.wx_keyword wx_keyword = wbll.GetModel(keyword);
            if (wx_keyword != null)
            {
                if (wx_keyword.msg_type == Enums.MsgType.text.ToString())
                {
                    AppendResponseText(wx_keyword.answer);
                }
                else if (wx_keyword.msg_type == Enums.MsgType.news.ToString())
                {
                    AppendResponseArticles(wx_keyword);
                }
            }
            //回答不上来时的回复
            else
            {
                if (Config.wx_config.un_answer_is_keyword == 1)
                {
                    AppendResponseByKeyword(Config.wx_config.un_answer_keyword);
                }
                else
                {
                    AppendResponseText(Config.wx_config.un_answer_msg);
                }
            }
        }

        /// <summary>
        /// 封装纯文本回复
        /// </summary>
        /// <param name="wx_keyword"></param>
        /// <param name="responseXml"></param>
        /// <returns></returns>
        public void AppendResponseText(string txt)
        {
            responseXml.MsgType = Enums.MsgType.text.ToString();
            responseXml.Content = txt;
        }

        /// <summary>
        /// 封装图文回复
        /// </summary>
        /// <param name="wx_keyword"></param>
        /// <param name="responseXml"></param>
        /// <returns></returns>
        public void AppendResponseArticles(Model.wx_keyword wx_keyword)
        {
            BLL.article abll = new BLL.article();
            List<xml.item> lst = new List<xml.item>();
            string[] idArr = wx_keyword.article_id.Split(',');
            if (idArr.Length > 0)
            {
                foreach (string s in idArr)
                {
                    int id = Convert.ToInt32(s);
                    Model.article article = abll.GetModel(id);
                    xml.item item = new xml.item();
                    item.Title = article.title;
                    item.Description = article.seo_desc;
                    item.PicUrl = NodesHandle.HandleImgUrl(article.img_url, Config.webset.site_domain);
                    item.Url = NodesHandle.HandleLinkUrl(article.id, Config.webset.site_domain, Config.site_info.EnginePage);
                    lst.Add(item);
                }
            }
            responseXml.MsgType = Enums.MsgType.news.ToString();
            responseXml.ArticleCount = lst.Count.ToString();
            responseXml.Articles = lst;
        }

        /// <summary>
        /// 第一次关注时增加会员信息
        /// </summary>
        /// <param name="openId"></param>
        public void AddMemberInfo(string openId)
        {
            BLL.member bll = new BLL.member();

            if (!bll.Exists(openId))
            {
                UserInfo info = UserInfo.GetUserInfo(openId);

                Model.member member = new Model.member();
                member.user_name = openId;
                member.user_pwd = StringHelper.GeneratePassword(8);
                member.nickname = info.nickname;
                member.sex = UserInfo.GetSex(info.sex);
                member.city = info.city;
                member.province = info.province;
                member.figure_url = info.headimgurl;
                member.reg_time = DateTime.Now.ToString();
                member.status = 2;
                bll.Add(member);
            }
        }


        #region ---
        public string GetMapInfo(string x, string y)
        {
            try
            {
                string xml = string.Empty;
                string param = string.Empty;
                string url = "http://maps.googleapis.com/maps/api/geocode/xml";
                param = "latlng=" + x + "," + y + "&language=zh-CN&sensor=false";
                xml = HttpHelper.HttpPost(url, param);
                XmlDocument document = new XmlDocument();
                document.LoadXml(xml);
                XmlElement documentElement = document.DocumentElement;
                if (documentElement.SelectSingleNode("status").InnerText == "OK")
                {
                    XmlNodeList childNodes = documentElement.SelectSingleNode("/GeocodeResponse").ChildNodes;
                    for (int i = 0; i < childNodes.Count; i++)
                    {
                        XmlNode node = childNodes[i];
                        if (node.Name != "status")
                        {
                            string innerText = "0";
                            for (int j = 0; j < node.ChildNodes.Count; j++)
                            {
                                for (int k = 0; k < node.ChildNodes[j].ChildNodes.Count; k++)
                                {
                                    XmlNode node2 = node.ChildNodes[j].ChildNodes[k];
                                    if (node2.Name == "long_name")
                                    {
                                        innerText = node2.InnerText;
                                    }
                                    else if (node2.InnerText == "locality")
                                    {
                                        return innerText;
                                    }
                                }
                            }
                            return innerText;
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                FileHelper.WriteLogTxt("map异常:" + exception.Message.ToString() + "Struck:" + exception.StackTrace.ToString(), "~/log.txt");
                return "0";
            }
            return "0";
        }
        #endregion
    }
}
